from http.client import responses
from app.extensions import get_db
from app.models.Clas import Clas
from app.services.ClasService import ClasService
from fastapi import APIRouter
from fastapi.responses import JSONResponse
from app.schemas.Clas import ClasSchema, ClasCreate

clas_router = APIRouter(prefix="/clas", tags=["班级管理"])
@clas_router.get("/",summary="搜索班级" )
def get_by_keyword(keyword: str = ""):
    with get_db() as db:
        svc = ClasService(db)
        responses = svc.get_by_keyword(keyword)
        return JSONResponse(
            content={
                "data": [ClasSchema.model_validate(item).model_dump() for item in responses["data"]],
                "message": responses["message"]
            },
            status_code=responses["code"]
        )


@clas_router.put("/{clas_id}", summary="修改班级")
def update_clas(clas_id: int, clas: ClasCreate):
    with get_db() as db:
        svc = ClasService(db)
        responses = svc.update_clas(clas_id, clas.name)
        return JSONResponse(
            content={
                "data": responses["data"],
                "message": responses["message"]
            },
            status_code=responses["code"]
        )



@clas_router.post("/{clas_name}", summary="增加班级")
def add_clas(clas_name):
    with get_db() as db:
        svc = ClasService(db)
        response = svc.add_clas(clas_name)
        return JSONResponse(
            content={
                "data": response["data"],
                "message": response["message"]
            },
            status_code=response["code"]
        )

def update_clas(clas_id, new_name):
    with get_db() as db:
        svc = ClasService(db)
        response = svc.update_clas(clas_id,new_name)
        return response

@clas_router.delete("/{clas_id}", summary="删除班级")
def delete_clas(clas_id: int):
    with get_db() as db:  # 链接数据库
        svc = ClasService(db)
        response = svc.delete_clas(clas_id)
        return JSONResponse(
            content={
                "data": response["data"],
                "message": response["message"]
            },
            status_code=response["code"]
        )